package com.homestead.client;

import java.util.Random;

/**
 * @author HanBin_Yang
 * @since 2021/3/20 18:20
 */
public class SortingHelper {
    public static <E extends Comparable<E>> boolean isSorted(E[] arr) {
        for (int i = 1; i < arr.length; i++) {
            if(arr[i-1].compareTo(arr[i]) > 0) {
                return false;
            }
        }
        return true;
    }

    public static Integer[] generateRandomArray(int n) {
        Integer[] arr = new Integer[n];
        for (int i = 0; i < n; i++) {
            int num = new Random().nextInt(Integer.MAX_VALUE);
            arr[i] = num;
        }
        return arr;
    }

    public static <E extends Comparable<E>> void sortTest(String sortName, E[] arr) {
        long time = System.nanoTime();
        if ("selectionSort".equals(sortName)) {
            AlgorithmUtil.selectionSort(arr);
        } else if("insertionSort".equals(sortName)) {
            AlgorithmUtil.insertionSort(arr);
        }

        time = System.nanoTime() - time;

        double timeResult = time / 1000000000.0;

        if (!isSorted(arr)) {
            throw new RuntimeException(sortName + "failed");
        }
        System.out.println(String.format("%s , n = %d : %f s", sortName, arr.length, timeResult));
    }
}
